<?php
include_once 'questionario.php';
include_once 'model.php';

session_start();
$quest= new questionario();
$errori= array();

// LETTURA FORM 
foreach ($_REQUEST as $k => $v) {
	if( isset($quest[$k]))		
  		$quest[$k]=$v;
}

//var_dump($quest);

$_SESSION['questionario']=$quest;

// VALIDAZIONE SERVER
$er = array();

//controllo codice
$codice_errato=true;
if(isset($_REQUEST['codice'])){
	$codice = $_REQUEST['codice'];	
	//$codex = base_convert($codice,36,10);
	if(strlen($codice)>=11){
		$ente = substr($codice, 0,5);
		$prog = substr($codice, 5);
	}
	$resto = base_convert($prog,36,10)%base_convert($ente,36,10);
	if($resto == 0)
		$codice_errato=false;
}
/*
if($codice_errato){
	array_push($er,"$prog");
	array_push($er,base_convert($prog,36,10));
	array_push($er,"$ente");
	array_push($er,base_convert($ente,36,10));
	array_push($er,"$resto");
	array_push($er,'codice_errato');
}else {
	array_push($er,"$prog");
	array_push($er,"$ente");
	array_push($er,"$resto");
	array_push($er,'codice_ok');
}
*/

if($codice_errato){
	array_push($er,'codice');
}
	
foreach ($_REQUEST as $k => $v) {
  if(!$quest->isValid($k))
  	array_push($er,$k);
}
$quest->setErrors($er);

if(count($quest->getErrors())>0){
	header( "Location: questionario_form.php" );
	return;
}

$urlxml = "./resources/config.xml";
$config= new SimpleXmlElement($urlxml,1,true);
$dbname = $config->database->name;
$user = $config->database->user;
$pass = $config->database->password;
	

if(isset($_REQUEST['azione'])){
	$action = $_REQUEST['azione'];
	$model = new Model($dbname,$user,$pass);
	switch ($action) {
		case 'insert':
			if($model->checkUsedCode($quest)){
				header( "Location: error.php?msg=codice_duplicato" );
				return;
			}
			$model->insertUpdate($quest);
			$model->close();
			header( "Location: inviato.php" );
			return;
		break;
		case 'continua':
			// TODO legge 
			header( "Location: questionario_form.php" );
			return;
		break;
		default:
			header( "Location: error.php?msg=errore_generico" );
		break;
	}
} else
	header( "Location: error.php" );
?>